import React, {Component} from 'react';
import T from 'prop-types'

import CONFIG from "./config"

import Toolbar from "./CKEBar/index"

export default class WeaCKEditorAppend extends Component {
    constructor(props) {
        super(props)
        this.editor = null
        this.html = ""
    }

    componentWillUnmount() {
        if (!this.editor) return

        this.editor.focusManager.hasFocus = false
    }

    render() {
        const {id, style, className, configBar, typeBar, onClickBar} = this.props
        return (
            <div id={id + "container"} style={style} className={className}>
                <div id={id}/>
                <Toolbar
                    id={id + '_bar'}
                    config={configBar}
                    onClick={onClickBar}
                    type={typeBar}
                    ref="toolbar"
                    insertHTML={this.InsertHTML}
                />
            </div>
        )
    }

    GetContents = () => {
        if (!this.editor) return

        return this.editor.getData()
    }

    SetContents = (contents) => {
        if (!this.editor) return

        this.editor.setData(contents)
    }

    InsertHTML = (html, isClear) => {
        if (!this.editor) return

        // Check the active editing mode.
        if (this.editor.mode == 'wysiwyg') {

            // Insert as html.
            if (isClear) this.editor.setData(html)
            else this.editor.insertHtml(html);
        } else {
            alert('You must be in WYSIWYG mode!');
        }
    }

    InsertText = (text) => {
        if (!this.editor) return

        // Check the active editing mode.
        if (this.editor.mode == 'wysiwyg') {

            // Insert as plain text.
            this.editor.insertText(text);
        } else {
            alert('You must be in WYSIWYG mode!');
        }
    }

    ExecuteCommand = (commandName) => {
        if (!this.editor) return

        // Check the active editing mode.
        if (this.editor.mode == 'wysiwyg') {

            // Execute the command.
            this.editor.execCommand(commandName);
        }
        else
            alert('You must be in WYSIWYG mode!');
    }

    CheckDirty = () => {
        if (!this.editor) return

        // Checks whether the current editor content contains changes when compared to the content loaded into the editor at startup.
        return this.editor.checkDirty()
    }

    ResetDirty = () => {
        if (!this.editor) return

        // Resets the "dirty state" of the editor.
        this.editor.resetDirty()
    }

    CountEditor = () => {
        let count = 0
        for (let editor in CKEDITOR.instances) {
            count++
        }
        return count
    }

    RemoveEditor = (hasToolbar) => {
        if (!this.editor) return

        this.editor.focusManager.hasFocus = false
        // Retrieve the editor content. In an Ajax application this data would be sent to the server or used in any other way.
        this.html = this.editor.getData()

        let toolbar = this.refs.toolbar

        // Destroy the editor.
        this.editor.destroy()
        this.editor = null

        toolbar.clear = true
        if (hasToolbar) {
            return {
                content: this.html,
                toolbar: toolbar.value
            }
        }
        return this.html
        //return html
    }

    get instance() {
        return this.editor
    }

    get instances() {
        return CKEDITOR.instances
    }

    CreateEditor = (html) => {
        const {
            id, type, config,
            onFocus, onBlur, onChange, onReady
        } = this.props

        if (this.editor) return

        this.html = html

        CKEDITOR.on('instanceReady', (event) => {
            if (onReady) {
                onReady()
            } else {
            }
        })

        this.editor = CKEDITOR.appendTo(id, CONFIG[type](config), this.html)

        this.editor.focusManager.hasFocus = false

        this.editor.on('focus', function (event) {
            if (onFocus) {
                onFocus()
            } else {
            }
        })

        this.editor.on('blur', function (event) {
            if (onBlur) {
                onBlur()
            } else {
            }
        })

        this.editor.on('change', function (event) {
            if (onChange) {
                onChange()
            } else {
            }
        })

        return this.editor.name
    }
}

WeaCKEditorAppend.propTypes = {
    id: T.string,//id或name
    type: T.string,//类型
    config: T.object,//自定义配置

    //当调用这些方法的时候，你需要bind(this)
    onFocus: T.function,//聚焦函数
    onBlur: T.function,//失焦函数
    onChange: T.function,//文本内容变更函数
}

WeaCKEditorAppend.defaultProps = {
    id: "weackeditor",
    type: "default"
}

WeaCKEditorAppend.ref = {
    GetContents: T.function,//return: <string> html
    SetContents: T.function,//params: <string> contents
    InsertHTML: T.function,//params: <string> html
    InsertText: T.function,//params: <string> text
    ExecuteCommand: T.function,//params: <string> commond

    CountEditor: T.function,//return: <number>
    CreateEditor: T.function,//return: <string> name
    RemoveEditor: T.function,//return: <string> html

    CheckDirty: T.function,//return: <boolean>
    ResetDirty: T.function,

    instance: T.object,
    instances: T.array
}

//余留BUG：
//1.当存在多个不同的CKEditor，toolbar随实例的生命周期创建和消亡（暂时解决办法：外部控制整个实例的显示和隐藏）